package com.dx.as.common;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jwaoo on 2017/7/1.
 */

public class FragmentUtils {
    private static Map<String,SoftReference<Fragment>> map = new HashMap<String,SoftReference<Fragment>>();
    private static Fragment previousFragment;
    public static void goToFragment(Activity activity , Class<? extends Fragment> fragmentClass, int container){
        FragmentManager fragmentManager = activity.getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        String fragmentName = fragmentClass.getSimpleName();
        SoftReference<Fragment> soft = map.get(fragmentName);
        Fragment fragment=null;
        try{
            fragmentTransaction.hide(previousFragment);
            if (soft == null){
                fragment = fragmentClass.newInstance();
                fragmentTransaction.add(container, fragment);
                map.put(fragmentName, new SoftReference<Fragment>(fragment));
            }else{
                fragment = soft.get();
                fragmentTransaction.show(fragment);
            }
            previousFragment = fragment;
            fragmentTransaction.commit();
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static void putDefaultFragment(Activity activity ,int container ,Fragment fragment){
        FragmentManager fragmentManager = activity.getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        try{
            fragmentTransaction.add(container, fragment);
            fragmentTransaction.commit();
            previousFragment = fragment;
            map.put(fragment.getClass().getSimpleName(), new SoftReference<Fragment>(fragment));
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}
